<?php

declare(strict_types=1);

namespace App\RoomMessageBatchSend\Logic;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use App\WorkEmployee\Service\WorkEmployeeService;
use Base\Constants\ErrorCode;
use Base\Exception\CommonException;
use App\RoomMessageBatchSend\Service\RoomMessageBatchSendService;
use App\RoomMessageBatchSend\Queue\RoomMessageBatchSendQueue;

class StoreLogic
{
    /**
     * @Inject
     * @var RoomMessageBatchSendService
     */
    private $roomMessageBatchSend;

    /**
     * @Inject
     * @var WorkEmployeeService
     */
    private $workEmployee;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @Inject
     * @var RoomMessageBatchSendQueue
     */
    private $roomMessageBatchSendQueue;

    public function handle(array $params, array $user): bool
    {
        $corpId = $user['corp_id'];
        $tenantId = $user['tenant_id'];
        $employeeIds = (array) $params['employeeIds'];
        $employeeIds = explode(",",$params['employeeIds']);

        // 获取用户成员
        $employees = $this->workEmployee->getWorkEmployeesByIdCorpIdStatus($corpId, $employeeIds, 1, ['id', 'wx_user_id']);
        if (count($employees) !== count($employeeIds)) {
            throw new CommonException(ErrorCode::INVALID_PARAMS,'请先同步企业通讯录');
        }

        // 入库
        Db::beginTransaction();
        try {
            $employeeIdsStr = ! empty($params['employeeIds']) ? json_encode($params['employeeIds'], JSON_UNESCAPED_UNICODE) : '[]';
            $batchId = $this->roomMessageBatchSend->createRoomMessageBatchSend([
                'corp_id' => $corpId,
                'tenant_id' => $tenantId,
                'user_id' => $user['user_id'],
                'user_name' => $user['user_name'],
                'employee_ids' => $employeeIdsStr,
                'batch_title' => $params['batchTitle'],
                'content' => json_encode($params['content'], JSON_UNESCAPED_UNICODE),
                'send_way' => $params['sendWay'],
                'definite_time' => $params['definiteTime'],
                'create_time' => date('Y-m-d H:i:s'),
            ]);

            $delay = 0;
            if ((int) $params['sendWay'] === 2) {
                $delay = strtotime($params['definiteTime']) - time();
                $delay = $delay < 0 ? 0 : $delay;
            }

            $this->roomMessageBatchSendQueue->push(['batchId' => $batchId,'employeeIds'=>$employeeIds], $delay);
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '客户群消息群发创建失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, '客户群消息群发创建失败');
        }

        return true;
    }
}
